import {
	httpConfig
} from './env.js';
import md5 from 'js-md5';
import store from '@/store'


const base = {
	chooseImageUpload(sourceType, callback) {
		uni.chooseImage({
			count: 1,
			sizeType: ['original', 'compressed'],
			sourceType: sourceType || ['album', 'camera'],
			success: (res) => {
				uni.showLoading({
					mask: true,
					title: '加载中...'
				})
				uni.uploadFile({
					url: httpConfig.baseURL + '/ossFiles/avatar',
					filePath: res.tempFilePaths[0],
					name: 'file',
					header: {
						Authorization: `Bearer ${uni.getStorageSync('token')}`
					},
					formData: {},
					success: (uploadFileRes) => {
						uni.hideLoading()
						callback(JSON.parse(uploadFileRes.data).data)
					},
					fail: (err) => {
						uni.showToast({
							icon: 'none',
							title: '上传失败'
						})
					},
				})
			}
		})
	},
	uploadFile(filePath) {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: httpConfig.uploadUrl + '/common/upload',
				filePath: filePath,
				name: 'file',
				header: {},
				success: (uploadFileRes) => {
					resolve(JSON.parse(uploadFileRes.data).data)
				},
				fail: (err) => {
					reject(err)
				},
			})
		})
	},

	hiddenPhone(phoneNumber) {
		if (typeof phoneNumber !== 'string' || phoneNumber.length !== 11) {
			return phoneNumber;
		}
		return phoneNumber.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
	},

	hiddenIdCard(id_no) {
		return id_no.slice(0, 4) + '****' + id_no.slice(-4);
	},


	authNavigate(authStatus) {
		if (authStatus === 10 || authStatus === 20) {
			uni.navigateTo({
				url: '/pages/authentication'
			})
		} else if (authStatus === 30) {
			uni.navigateTo({
				url: '/pages/dataAuthentication'
			})
		} else {
			uni.showToast({
				icon: 'none',
				title: '认证已完成'
			})
		}
	},

	getMyDate(str) {
		var oDate = new Date(Number(str) * 1000),
			oYear = oDate.getFullYear(),
			oMonth = oDate.getMonth() + 1,
			oDay = oDate.getDate(),
			oHour = oDate.getHours(),
			oMin = oDate.getMinutes(),
			oSen = oDate.getSeconds(),
			oTime = oYear + '-' + base.addZero(oMonth) + '-' + base.addZero(oDay) + ' ' + base.addZero(oHour) +
			':' +
			base.addZero(oMin);
		return oTime;
	},
	addZero(num) {
		if (parseInt(num) < 10) {
			num = '0' + num;
		}
		return num;
	},
	debounce(func, time, immediate = false) {
		let timer;
		return (...args) => {
			if (timer) clearInterval(timer);
			if (immediate) {
				if (!timer) func.apply(this, args);
				timer = setTimeout(() => {
					timer = null;
				}, time);
			} else {
				timer = setTimeout(() => {
					func.apply(this, args);
				}, time);
			}
		};
	},
	numFormat(num) {
		num = num.toString().split("."); // 分隔小数点
		var arr = num[0].split("").reverse(); // 转换成字符数组并且倒序排列
		var res = [];
		for (var i = 0, len = arr.length; i < len; i++) {
			if (i % 3 === 0 && i !== 0) {
				res.push(","); // 添加分隔符
			}
			res.push(arr[i]);
		}
		res.reverse(); // 再次倒序成为正确的顺序
		if (num[1]) { // 如果有小数的话添加小数部分
			res = res.join("").concat("." + num[1]);
		} else {
			res = res.join("");
		}
		return res;
	},

	generateSign(params, privateKey) {
		// 1. 移除空值与 sign 字段
		const filteredParams = {};
		for (let key in params) {
			const val = params[key];
			if (val !== undefined && val !== null && val !== '' && key !== 'sign') {
				filteredParams[key] = val;
			}
		}

		// 2. 按 ASCII 码排序参数
		const sortedKeys = Object.keys(filteredParams).sort();

		// 3. 构造 stringA
		const stringA = sortedKeys.map(key => `${key}=${filteredParams[key]}`).join('&');

		// 4. 拼接私钥并加密
		const stringSignTemp = `${stringA}&key=${privateKey}`;
		const sign = md5(stringSignTemp).toUpperCase();

		return sign;
	},
	verifyMember() {
		const isMember = store.state.user.mainChartInfo.isMember
		if (isMember !== 1) {
			uni.showToast({
				icon: 'none',
				title: '您还不是会员，请先开通会员'
			})
			return false;
		} else {
			return true
		}
	},
	navigateTo(url) {
		uni.navigateTo({
			url: url
		})
	}
}


export default base;